import axios, { AxiosRequestConfig } from "axios";
import { Result } from "@/entity/Result";
import store from "@/vuex-store";

import { ElMessage } from "element-plus";

const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 10000,
});

instance.interceptors.request.use(
  function (config) {
    // 设置请求头 token
    if (store.state.user.token) {
      config.headers = {
        Authorization: store.state.user.token,
      };
    }

    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  function (response) {
    // 如果是返回请求返回文件类型，直接返回 response
    if (response.request.responseType === "blob") {
      return Promise.resolve(response);
    }

    const result = response.data as Result;

    if (result.success) {
      // 正常返回 data
      return Promise.resolve(result.data || result.message);
    } else {
      // 有错误产生
      ElMessage.error(result.message);

      return Promise.reject(result.message);
    }
  },
  function (error) {
    ElMessage.error(error.toString());

    return Promise.reject(error);
  }
);

function request<T = any>(options: AxiosRequestConfig) {
  return instance(options) as any as Promise<T>;
}

export default request;
